package com.javaweb.controller;

import com.alibaba.excel.EasyExcel;

import com.javaweb.common.ResponseResult;
import com.javaweb.dao.StudentDao;
import com.javaweb.model.Student;
import com.javaweb.upload.StudentUploadDto;
import com.javaweb.upload.StudentUploadListener;
import jakarta.servlet.http.HttpServletResponse;
import org.springframework.core.io.ByteArrayResource;
import org.springframework.core.io.Resource;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpStatus;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;

import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.net.URLEncoder;
import java.util.ArrayList;
import java.util.List;

/**
 * @desc:
 * @author: Ping
 * @date: 2024/11/20 19:46
 */
@Controller
@RequestMapping("file")
public class FileController {
    /**
     * studentDao 存储学生数据
     */
    private StudentDao studentDao ;

    @PostMapping("excel-upload")
    @ResponseBody
    public ResponseResult<String> excelUpload(MultipartFile file) {
        try {
            EasyExcel.read(file.getInputStream(), StudentUploadDto.class, new StudentUploadListener(studentDao)).sheet().doRead();
            return ResponseResult.ok("文件上传成功");
        } catch (IOException e) {
            return ResponseResult.error(HttpStatus.INTERNAL_SERVER_ERROR, "文件上传失败");
        }
    }

    @GetMapping("/download")
    public ResponseEntity<Resource> downloadExcel(HttpServletResponse response) throws IOException {
        // 准备数据
        List<Student> data = new ArrayList<>();
        for (int i = 0; i < 1000; i++) {
            Student stu = Student.builder()
                    .age(18)
                            .phone("123456789")
                                    .gender("男")
                                            .name("张三")
                                                    .build() ;
            data.add(stu);
        }

        // 使用EasyExcel写入数据到输出流
        ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
        EasyExcel.write(outputStream, Student.class).sheet("Sheet1").doWrite(data);

        // 设置响应头
        HttpHeaders headers = new HttpHeaders();
        headers.add(HttpHeaders.CONTENT_DISPOSITION, "attachment;filename=" + URLEncoder.encode("用户数据.xlsx", "UTF-8"));
        headers.add(HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_OCTET_STREAM_VALUE);

        // 创建响应实体
        Resource resource = new ByteArrayResource(outputStream.toByteArray());
        return ResponseEntity.ok()
                .headers(headers)
                .body(resource);
    }






}
